//index.js
//获取应用实例
const app = getApp()
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
  data: {
    hasUserInfo: false,
    userInfo: {},
    swiperImg: [],
    sexArr: ["男","女","全部"],
    cityArr: [],
    likeNumArr: ["升序","降序"],  // 升序：ASC  降序：DESC
    sex: "全部",
    cityName: "全部",
    bigImgShow: false,
    userList: [],  // 列表
    pageNo: 1,
    totalPage: "",
    bigImg: "", // 大图
    maskSex: "",
    maskAge: "",
    maskCity: "",
    currentUser: -1,
    priseOrder: "ASC", // 点赞顺序
  },
 
  onLoad: function () {
    // 判断用户是否已经授权
    wx.getUserInfo({
      success: res => {
        app.globalData.userInfo = res.userInfo
        var userInfo = res.userInfo;
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: false
        })
        
        // 定位
        wx.getLocation({
          type: 'wgs84',
          success: res => {
            const latitude = res.latitude;
            const longitude = res.longitude;
            this.getAddress(latitude, longitude, userInfo);
            app.globalData.latitude = latitude;
            app.globalData.longitude = longitude;
          },
          fail: res => {
            console.log(res);
            app.showError("定位失败")
          }
        });
      },
      fail: res =>{
        this.setData({
          hasUserInfo: true
        })
      }
    });
    this.getList(this.data.cityName);
    
    this.getSwiper();
    this.getCode();
    this.setData({
      uploadImgUrl: ""
    })
    
  },
  
  // 授权登陆
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    var userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: false
    });
    // this.login(e.detail.userInfo);
    // 定位
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        const latitude = res.latitude;
        const longitude = res.longitude;
        this.getAddress(latitude, longitude, userInfo);
        app.globalData.latitude = latitude;
        app.globalData.longitude = longitude;
      },
      fail: res => {
        console.log(res);
        app.showError("定位失败")
      }
    });
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 显示顶部刷新图标   
    // wx.showNavigationBarLoading();
    // this.update();
    this.setData({
      pageNo: 1,
      userList: []
    });
    this.getList(this.data.cityName);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      pageNo: this.data.pageNo + 1
    });
    if (this.data.pageNo <= this.data.totalPage) {
      this.getList(this.data.cityName);
    }

  },
  

  // 获取轮播图
  getSwiper: function () {
    wx.request({
      url: app.globalData.baseUrl + '/data/logoList',
      success: res => {
        if (res.data && res.data.length > 0) {
          this.setData({
            swiperImg: res.data
          })
        }
      },
      fail: res => {
        console.log(res);
      }
    })
  },

  // 改变性别
  changeSex(e){
    var sex = "";
    if (e.detail.value === "0") {
      sex = "男"
    } else if (e.detail.value === "1") {
      sex = "女"
    } else {
      sex = "全部"
    }
    this.setData({
      sex: sex,
      userList: [],
      pageNo: 1,
    });
    this.getList(this.data.cityName);
  },

  // 选择城市
  changeCity(e){
    var cityName = "";
    if (e.detail.value[0] === "全部"){
      cityName = e.detail.value[0];
      app.globalData.chooseCity = app.globalData.locationCity;
    }else{
      if (e.detail.value[0].split("市").length > 1) {
        cityName = e.detail.value[0].split("市")[0];
        app.globalData.chooseCity = e.detail.value[0].split("市")[0];
      } else {
        if (e.detail.value[1] === "全部") {
          app.showError("请选择确定的市")
          app.globalData.chooseCity = app.globalData.locationCity;
        } else {
          cityName = e.detail.value[1].split("市")[0]
          app.globalData.chooseCity = e.detail.value[1].split("市")[0]
        }
      }
    }
    this.setData({
      cityName: cityName
    });
    
    this.setData({
      userList: [],
      pageNo: 1,
    })
    this.getList(cityName);
  },

  // 点赞顺序（升序或者降序）
  changeLike(e){
    var order = "";
    if(e.detail.value === "0"){
      order = "ASC"
    }else{
      order = "DESC"
    }
    this.setData({
      priseOrder: order,
      userList: [],
      pageNo: 1,
    })
    this.getList(this.data.cityName);
  },

  // 查看大图
  bigImgShow(e){
    var index = e.currentTarget.dataset.index;
    var userList = this.data.userList;
    if (userList[index].status === "PERSON_SE"){
      app.globalData.detail = userList[index];
      wx.navigateTo({
        url: '../detail/detail?type=detail',
      })
    }else{
      this.setData({
        bigImgShow: true,
        bigImg: userList[index].img_url,
        maskSex: userList[index].sex,
        maskAge: userList[index].age,
        maskCity: userList[index].city,
        currentUser: index
      });
    }
  },

  // 隐藏大图
  marskHide(){
    this.setData({
      bigImgShow: false
    })
  },

  // 弹框内点赞
  maskZan(){
    this.dianZan(this.data.userList[this.data.currentUser].id, this.data.currentUser);
  },

  // 点赞
  zanTap(e){
    this.dianZan(e.currentTarget.dataset.id,e.currentTarget.dataset.index);
  },

  // 点赞
  dianZan(id,index){
    wx.request({
      url: app.globalData.baseUrl + '/data/newDz',
      header: {
        unicorn: app.globalData.token
      },
      data: {
        id: id
      },
      success: res => {
        console.log(res)
        if (res.data) {
          if (res.data.errCode === "00000") {
            wx.showToast({
              title: '点赞成功',
            });
            this.data.userList[index].like_count += 1;
            this.setData({
              userList: this.data.userList
            })
          } else if (res.data.errCode === "10010") {
            app.showError("请不要重复点赞");
          } else {
            app.showError("参数错误");
          }
        }
      },
      fail: res => {
        console.log(res)
        app.showError("服务器错误")
      }
    })
  },

  // 打招呼
  greetTap(e){
    var index = e.currentTarget.dataset.index;
    // app.globalData.chatDetail = this.data.userList[index];
    if(this.data.userList[index].greet === 1){
      app.showError("此人不允许打招呼");
    }else{
      this.isPerfectPerson(this.data.userList[index].uid);
    }
  },

  // 弹框内打招呼
  maskGreet(){
    // app.globalData.chatDetail = this.data.userList[this.data.currentUser];
    if(this.data.userList[this.data.currentUser].greet === 1){
      app.showError("此人不允许打招呼");
    }else{
      this.isPerfectPerson(this.data.userList[this.data.currentUser].uid);
    }
  },

  // 判断个人资料是否已完善
  isPerfectPerson(uid){
    wx.request({
      url: app.globalData.baseUrl + '/data/IsPerfectPerson',
      header: {
        unicorn: app.globalData.token
      },
      success: res => {
        this.imAddUser(uid);
        this.getOpenId(uid);
        if (res.data && res.data === true) {
          wx.navigateTo({
            // url: '../chatList/chatList',
            url: '../chat/chat',
          })
        } else {
          wx.navigateTo({
            url: '../personalInfo/personalInfo',
          });
          app.globalData.chatToUid = uid;
        }
      },
      fail: res => {
        console.log(res);
        app.showError("服务器错误")
      }
    })
  },

  // 上屏
  goLaunch(e){
    var index = e.currentTarget.dataset.index;
    if(index === 0){
      wx.navigateTo({
        url: '../myCollect/myCollect',
      })
    }else{
      wx.navigateTo({
        url: '../launch/launch',
      })
    }
    
  },

  // 个人中心
  goUserInfo(){
    wx.navigateTo({
      url: "../userInfo/userInfo"
    })
  },

  // 消息
  goChatList(){
    wx.navigateTo({
      url: '../chatList/chatList',
    })
  },

  // 定位
  getAddress(latitude, longitude, userInfo) {
    qqmapsdk = new QQMapWX({
      key: 'ZWHBZ-CL5KG-RI6QY-IAYDI-UT725-AIFF5'
    });
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: res => {
        const province = res.result.address_component.province;   // 省
        const city = res.result.address_component.city;   // 市
        const district = res.result.address_component.district;  // 区
        // this.setData({
        //   cityName: city.split("市")[0]
        // })
        app.globalData.locationCity = city.split("市")[0];
        // this.getList(city.split("市")[0]);
        this.login(userInfo, city.split("市")[0]);
      },
      fail: res => {
        console.log(res)
      }
    })
  },

  // 获取列表
  getList(city) {
    wx.request({
      url: app.globalData.baseUrl + '/data/newIndexList',
      data: {
        pageNo: this.data.pageNo,
        pageSize: "4",
        sex: this.data.sex,
        city: city,
        sc: this.data.priseOrder  // ASC/DESC
      },
      success: res => {
        var userList = this.data.userList;
        this.setData({
          totalPage: res.data.TotalPage
        })
        if (res.data.data){
          for (var i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].birthday !== null && res.data.data[i].birthday !== "") {
              res.data.data[i].age = app.countAge(res.data.data[i].birthday.split(" ")[0]);

            } else {
              res.data.data[i].age = "0岁";
            }
            if (res.data.data[i].like_count > 9999) {
              res.data.data[i].like_count = "9999+";
            }
            userList.push(res.data.data[i])
          }
          this.setData({
            userList: userList,
          })
          // 停止下拉动作
          wx.stopPullDownRefresh();
          wx.hideLoading();
        }
      },
      fail: res => {
        console.log(res)
      }
    })
  },

  // 登陆
  login: function (userInfo,city) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.login({
      success: res => {
        wx.request({
          url: app.globalData.baseUrl + '/data/login',
          data: {
            code: res.code,
            nickname: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl,
            sex: app.globalData.userInfo.gender === 2 ? '女' : '男',
            city: city,
          },
          success: res => {
            wx.hideLoading();
            if (res.data && res.data.errCode == "00000") {
              var token = res.data.token;
              app.globalData.token = token;
              // this.importUser(token);
              this.getMyDetail();
            } else {
              // todo 登录失败测试
              app.showError("登陆失败");
            }
          },
          fail: res => {
            console.log(res);
          }
        })
      }
    })
  },

  // 获取临时令牌code
  getCode: function () {
    wx.request({
      url: app.globalData.url + '/oauth/authorize',
      method: "GET",
      data: {
        'response_type': 'code',
        'client_id': "winpluszt",
        'redirect_uri': "www.tihe-china.com"
      },
      success: res => {
        if (res.data.data.code) {
          this.getAccessToken(res.data.data.code);
        }
      },
      fail: res => {
        console.log(res);
      }
    })

  },
  // 获取access_token
  getAccessToken: function (code) {
    wx.request({
      url: app.globalData.url + '/oauth/token',
      method: "POST",
      data: {
        'code': code,
        'redirect_uri': "www.tihe-china.com",
        'grant_type': "authorization_code",
        'client_id': "winpluszt",
        'client_secret': "winpluszt"
      },
      success: res => {
        if (res.data.data.access_token) {
          app.globalData.accessToken = res.data.data.access_token;
        }
      },
      fail: res => {
        console.log(res);
        app.showError("服务器出错，请稍后再试");
      }
    })
  },

  // 把用户导入到腾讯云IM
  importUser(uid) {
    wx.request({
      url: app.globalData.baseUrl + '/tim/accountImport',
      data:{
        uid: uid,
      },
      success: res => {
        // console.log(res)
      },
      fail: res => {
        console.log(res)
      }
    })
  },

  // 获取当前用户资料
  getMyDetail() {
    wx.request({
      url: app.globalData.baseUrl + '/data/getUserByToken',
      header: {
        unicorn: app.globalData.token
      },
      success: res => {
        if (res.data) {
          app.globalData.myDetail = res.data;
          this.importUser(res.data.uid);
          // this.imAddUser(res.data.uid);
        }
      },
      fail: res => {
        console.log(res);
        app.showError("服务器错误");
      }
    })
  },


  // 获取openid
  getOpenId(uid){
    wx.request({
      url: app.globalData.baseUrl + '/data/getUserByUid',
      data:{
        uid: uid
      },
      success: res =>{
        console.log(res)
        if(res.data){
          app.globalData.chatDetail = res.data;
        }
      },
      fail: res =>{
        console.log(res)
      }
    })
  },

  // 判断用户是否注册腾讯云IM
  imAddUser(uid) {
    wx.request({
      url: app.globalData.baseUrl + '/tim/addUser',
      data: {
        uid: uid
      },
      success: res => {
        console.log(res);
        if (res.data === true) {
         
        } else {
          app.showError("资料提交成功，但发起聊天失败")
        }
      },
      fail: res => {
        console.log(res)
      }
    })
  }

  
  

})
